﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace Freshome.m.vws
{
    /// <summary>
    /// Pairaw.xaml 的交互逻辑
    /// </summary>
    public partial class Pairaw : Window
    {
        private BackgroundWorker _ld = new BackgroundWorker();
        private const string _ep = "wsHttp_IMultint";
        private readonly fox.Userole _ur = null;
        private readonly fox.Helproxy<Rmt.IMultint> _hp;
        private short _id;

        public Pairaw(short mid, string nm, fox.Userole ur)
        {
            InitializeComponent();
            this._id = mid;
            this._ur = ur;
            this.Title = nm + "搭配表";
            this._hp = new fox.Helproxy<Rmt.IMultint>(ur);
            topanel.Loaded += new RoutedEventHandler(topanel_Loaded);
            this._ld.DoWork += new DoWorkEventHandler(Load_DoWork);
            this._ld.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Load_WorkerCompleted);
            topanel.DataContext = this;
        }
        private ObservableCollection<mds.WrongPair> _wrong = new ObservableCollection<mds.WrongPair>();
        public ObservableCollection<mds.WrongPair> WrongPairs
        {
            get { return this._wrong; }
        }
        private ObservableCollection<mds.RightPair> _right = new ObservableCollection<mds.RightPair>();
        public ObservableCollection<mds.RightPair> RightPairs
        {
            get { return this._right; }
        }
        public bool Readonly
        {
            get { return !this._ur.IsJunior; }
        }
        public bool Enabled
        {
            get { return this._ur.IsJunior; }
        }
        void topanel_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_ld.IsBusy)
            {
                _ld.RunWorkerAsync();
                this.dgw.IsReadOnly = true;
                this.dgr.IsReadOnly = true;
            }
        }
        void Load_DoWork(object sender, DoWorkEventArgs e)
        {
            _hp.Asyncall(cln =>
            {
                e.Result = cln.GetPairaws(this._id);
            }, new Rmt.MultintClient(_ep));
        }
        // The Recipe Loading finished
        void Load_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null) MessageBox.Show(e.Error.Message, "数据服务");
            else
            {
                var rts = e.Result as Rmt.Pairaw[];
                if (rts != null)
                {
                    RefreshPairaws(rts.Where(m => m.Taboo == false), _right);
                    RefreshPairaws(rts.Where(m => m.Taboo == true), _wrong);
                }
            }
            this.dgw.IsReadOnly = !this._ur.IsJunior;
            this.dgr.IsReadOnly = !this._ur.IsJunior;
        }
        private void RefreshPairaws<T>(IEnumerable<Rmt.Pairaw> new_s, ObservableCollection<T> old_s) where T : mds.Pairaw, new()
        {
            for (int i = old_s.Count - 1; i >= 0; i--)
            {
                if (old_s[i].Created) continue;
                var raw = new_s.FirstOrDefault(m => m.Mid == old_s[i].Raw.Mid);
                if (raw != null) old_s[i].Refresh(raw);
                else old_s.RemoveAt(i);
            }
            foreach (var raw in new_s)
            {
                var row = old_s.FirstOrDefault(m => m.Raw.Mid == raw.Mid);
                if (row == null)
                {
                    row = new T();
                    row.Raw.Mid = raw.Mid;
                    row.Refresh(raw);
                    old_s.Add(row);
                }
            }
        }
        // Save created or updated rows
        private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _wrong.Any(m => (m.Created && m.IsValid) || m.Updated) || _right.Any(m => (m.Created && m.IsValid) || m.Updated);
        }
        private void Save_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var raws = (from m in _wrong where (m.IsValid && m.Created) || m.Updated select m.Raw)
                .Union(from m in _right where (m.IsValid && m.Created) || m.Updated select m.Raw);
            if (raws.Count() > 0)
            {
                short mid = short.MinValue; // 为新加记录预设Mid
                foreach (var raw in raws)
                {
                    if (raw.Mid == default(int))
                    {
                        raw.Mid = mid++;
                        raw.Jmx = this._id;
                    }
                    raw.Stamp = string.Format("{0}+{1}", this._id, raw.Mate);
                }
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SavePairaws(raws.ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    fox.Kitools.Replace<mds.Pairaw, Rmt.Pairaw>(rts, _wrong.Where(m => (m.IsValid && m.Created) || m.Updated), "错误搭配");
                    fox.Kitools.Replace<mds.Pairaw, Rmt.Pairaw>(rts, _right.Where(m => (m.IsValid && m.Created) || m.Updated), "正确搭配");
                }
            }
        }
        // 删除
        private void Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg != null)
            {
                if (dg.Name == "dgw") e.CanExecute = dgw.SelectedItem != null;
                else e.CanExecute = dgr.SelectedItem != null;
            }
            else e.CanExecute = false;
        }
        private void Delete_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg != null)
            {
                if (dg.Name == "dgr")
                {   // 正确搭配
                    Deletentity(dg.ItemsSource as ObservableCollection<mds.RightPair>, dgr.SelectedItem as mds.RightPair, "正确搭配");
                }
                else
                {   // 错误搭配
                    Deletentity(dg.ItemsSource as ObservableCollection<mds.WrongPair>, dgw.SelectedItem as mds.WrongPair, "错误搭配");
                }
            }
        }
        private void Deletentity<T>(ObservableCollection<T> prs, T pr, string titlead) where T : mds.Pairaw
        {
            if (pr != null && prs != null)
            {
                if (pr.Created == false)
                {
                    if (MessageBox.Show(string.Format("{0}({1})的数据将被删除，继续吗？", titlead, pr.Mate), titlead,
                        MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        _hp.Syncall(cln =>
                        {
                            if (cln.DelePairaw(pr.Raw.Mid)) prs.Remove(pr);
                        }, new Rmt.MultintClient(_ep));
                    }
                }
                else prs.Remove(pr);
            }
        }
    }
}
